<?php
// 通用函数

/**
 * Get date
 * 
 * @param  $strDate
 * @param  $strFormat
 * @return string
 * @author 李鑫辉
 */
function get_date( $strDate, $strFormat = 'Y-m-d' ) {

    if ( ! $strDate ) {

        return false;
    }

    return date($strFormat, strtotime($strDate));
}

/**
 * Set array key
 * Changes in two-dimensional array, to do with the specified key name
 * 
 * @param  $arrData
 * @param  $strKey
 * @return array
 * @author 李鑫辉
 */
function set_array_key( $arrData, $strKey = 'id' ) {
    
    if ( ! is_array($arrData) ) {
        return false;
    }
    
    $arr_result = array();
    foreach ( $arrData as $key => $sub ) {
        $arr_result[$sub[$strKey]] = $sub;
    }
    
    return $arr_result;
}

/**
 * Set array key multi
 * Changes in two-dimensional array, to do with the specified key name
 * 
 * @param  $arrData
 * @param  $strKey
 * @return array
 * @author andy
 */
function set_array_key_multi( $arrData, $strKey = 'id' ) {

    if ( ! is_array($arrData) ) {

        return false;
    }

    foreach ( $arrData as $sub ) {

        $result[$sub[$strKey]][] = $sub;
    }

    return $result;
}

/**
 * Implode array key
 * 
 * @param  $arrData
 * @param  $strKey
 * @param  $strDelimiter
 * @return string
 * @author andy
 */
function implode_array_key( $arrData, $strKey = 'id', $strDelimiter = ' ' ) {

    if ( ! is_array($arrData) ) {

        return false;
    }

    foreach ( $arrData as $sub ) {

        $arr_result[] = $sub[$strKey];
    }

    return implode($strDelimiter, $arr_result);
}

/**
 * 截取字符串
 * 
 * @param  $strParam
 * @param  $intLength
 * @param  $strExt
 * @return string
 * @author 李鑫辉
 */
function cut_str( $strParam, $intLength = 50, $strExt = '...' ) {
    
    return mb_substr($strParam, 0, $intLength, 'utf8') . $strExt;
}

/**
 * Split string
 * 
 * @param  $strParam
 * @param  $strDelimiter
 * @param  $intReturnKey
 * @return string
 * @author 李鑫辉
 */
function split_str( $strParam, $strDelimiter = '|', $intReturnKey = 0 ) {
    
    $arr_info = explode($strDelimiter, $strParam);
    
    return $arr_info[$intReturnKey];
}

/**
 * Remove xss
 *
 * @param  $strVal
 * @param  $strReplaceSeparator
 * @param  $isCleanSpecialStr
 * @return void
 * @author 李鑫辉
 */
function remove_xss( $strVal, $strReplaceSeparator = ' ', $isCleanSpecialStr = true ) {

    $str_val = strip_tags($strVal);
    
    if ( $isCleanSpecialStr ) {
        $str_val = str_replace(array(
                                     '`', '@', '#', '$', '%', '^', '&',
                                     '*', '(', ')', '+', '<', '>',
                                     '?', ',', '.', '/', ';', '\:', '\"',
                                     '|', '[', ']', '{', '}', '\n', '\t',
                                     '\f', '\v', '"'
                          
                                    ), $strReplaceSeparator, $str_val);
    }

    return trim($str_val);
}

/**
 * Get client ip
 * 
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function get_client_ip() {
    
    return $_SERVER['REMOTE_ADDR'];
}

/**
 * Write error msg
 * 
 * @param  $intStatus
 * @param  $strMsg
 * @return void
 * @author 李鑫辉
 */
function output_json_error( $intStatus, $strMsg = '' ) {
    
    exit(json_encode(array('status'=>$intStatus, 'content'=>$strMsg)));
}

/**
 * Write success msg
 * 
 * @param  $strMsg
 * @return void
 * @author 李鑫辉
 */
function output_json_succ( $strMsg = 'Success.' ) {
    
    exit(json_encode(array('status'=>0, 'content'=>$strMsg)));
}

/**
 * Write error msg, jsonp
 * 
 * @param  integer $status
 * @param  mixed   $msg
 * @return void
 * @author 李鑫辉
 */
function output_jsonp_error( $status, $msg = '', $strJsonpCallBack = 'jsonp_callback' ) {
    
    echo $strJsonpCallBack . '(' . json_encode(array('status'=>$status, 'content'=>$msg)) . ')';
    exit;
}

/**
 * Write msg, jsonp
 * 
 * @param  mixed  $msg
 * @param  string $strJsonpCallBack
 * @return void
 * @author 李鑫辉
 */
function output_jsonp_info( $msg = '', $strJsonpCallBack = 'jsonp_callback' ) {
    
    echo $strJsonpCallBack . '(' . json_encode(array('status'=>0, 'content'=>$msg)) . ')';
    exit;
}

/**
 * Ob get content
 * 
 * @param  string $strFile
 * @return string
 * @author 李鑫辉
 */
function ob_get_content( $strFile ) {
    
    ob_start();
    include $strFile;
    
    return ob_get_clean();
}

/**
 * Get current url
 * 
 * @param  void
 * @return void
 * @author 李鑫辉
 */
function get_current_url() {
    
    return 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

/**
 * Get file extention
 *
 * @param  string  $file
 * @return string
 * @author 李鑫辉
 */
function get_file_extention( $file ) {
    
    return substr(strrchr($file, '.'), 1);
}

/**
 * Get file name
 *
 * @param  string  $file
 * @return string
 * @author 李鑫辉
 */
function get_file_name( $file ) {
    
    return substr($file, 0, strrpos($file, '.'));
}

/**
 * 参数组合成字符串
 *
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function get_params_str() {
    
    $arr_args = func_get_args();
    return implode('|', $arr_args);
}

/**
 * 数组转字符串
 *
 * @param  $arrInfo
 * @return string
 * @author 李鑫辉
 */
function get_arr_to_str( $arrInfo ) {
    
    return print_r($arrInfo, true);
}

/**
 * Debug
 *
 * @param  array
 * @return string
 * @author 李鑫辉
 */
function debug( $arrInfo, $blnExit = false ) {
    
    echo '<h1>===== Debug start =====</h1><pre>' . print_r($arrInfo, true) . '</pre>';
    if ( $blnExit ) {
        exit('<h1>===== Debug end =====</h1>');
    }
}

/**
 * Connect memcache
 *
 * @param  $strServer
 * @return obj
 * @author 李鑫辉
 */
function connect_memcache( $strServer = '102' ) {

    return new memcache_server($strServer);
}

/**
 * Connect mysql
 *
 * @param  $strConnect
 * @return obj
 * @author 李鑫辉
 */
function connect_mysql( $strConnect = 'Mysql_102' ) {

    return _mysqllogon($strConnect);
}

/**
 * Close mysql
 *
 * @param  $objDb
 * @return void
 * @author 李鑫辉
 */
function close_mysql( $objDb ) {

    _mysqlclose($objDb);
}

/**
 * Query mysql
 *
 * @param  $objDb
 * @param  $strSql
 * @param  $arrBinds
 * @return array
 * @author 李鑫辉
 */
function query_mysql( $objDb, $strSql, $arrBinds = null ) {

    $res_stmt = _mysqlparse($objDb, $strSql);

    if ( is_array($arrBinds) ) {
        foreach ( $arrBinds as $key=>$val ) {
            _mysqlbindbyname($res_stmt, $key, $val);
        }
    }
    
    _mysqlexecute($res_stmt);
    
    while ( $arr_row = mysql_fetch_assoc($res_stmt) ) {
        $arr_info[] = $arr_row;
    }

    return $arr_info;
}

/**
 * Exec mysql
 *
 * @param  $objDb
 * @param  $strSql
 * @param  $arrBinds
 * @return string
 * @author 李鑫辉
 */
function exec_mysql( $objDb, $strSql, $arrBinds = null ) {

    $res_stmt = _mysqlparse($objDb, $strSql);
    
    if ( is_array($arrBinds) ) {
        foreach ( $arrBinds as $key=>$val ) {
            _mysqlbindbyname($res_stmt, $key, $val);
        }
    }
    
    return _mysqlexecute($res_stmt);
}


/**
 * App class
 * 
 * @author andy 
 */
class App {
    
    const APP_SUPPORT_IPHONE   = 1;// Iphone应用
    const APP_SUPPORT_IPAD     = 2;// Ipad应用
    const APP_SUPPORT_ALL      = 3;// 所有应用
    
    const APP_TYPE_ALL         = 0;// 所有应用
    const APP_TYPE_GAME        = 1;// 游戏应用
    const APP_TYPE_NOT_GAME    = 2;// 非游戏应用
    const APP_TYPE_RECOMMEND   = 3;// 推荐应用
    const APP_TYPE_ESSENTIAL   = 4;// 装机必备
    const APP_TYPE_PRICE       = 5;// 爱最贵
    
    const APP_CATEGORY_ID_GAME = 6014;// 游戏类别ID
    
    const APP_FILE_ID_MOBILE   = 10000;// 推广授权, 移动上使用
    
    private static $_cdn_url   = array(
                                       's1.izhushou.cn',
                                       's2.izhushou.cn',
                                       's3.izhushou.cn'
                                 );
    
    /**
     * Get app info
     * 
     * @param  $objDb
     * @param  $intAppId
     * @return array
     * @author 李鑫辉
     */
    public static function get_app_info( $objDb, $intAppId ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_info WHERE id = :id';
        $arr_info = query_mysql($objDb, $str_sql, array(':id'=>$intAppId));

        return $arr_info[0];
    }
    
    /**
     * Get app list info
     * 
     * @param  $objDb
     * @param  $intSupport    1: iphone, 2: ipad, 3: all
     * @param  $intType
     * 0: 所有应用
     * 1: game, 游戏应用
     * 2: 非游戏应用
     * 3: recommend, 推荐应用
     * 4: essential, 装机必备
     * 5: price, 价格排行, 爱最贵
     * @param  $intOrderBy
     * @param  $intPage
     * @param  $intPageSize
     * @param  $arrData
     * array(
     *       'order_by'    => '', // 排序
     *       'file_id'     => '', // 指定dsp, file_id = 10000
     *       'genre_id'    => '', // 类别
     *       'sub_genre'   => '', // 子类别
     *       'sub_type'    => '', // 1: new, 新增, 2: hot, 热门
     *       'get_total'   => '', // 返回总数
     *       'join_dsp'    => '', // 关联dsp表
     *       'app_ids'     => '', // App ids
     *       'app_id'      => '', // App id
     *       'search_word' => '', // 搜索关键词
     * )
     * @return array
     * @usage
     * $obj_db = connect_mysql();
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_RECOMMEND, 1, 1, 10);
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_ALL, 1, 1, 10, array('file_id'=>App::APP_FILE_ID_MOBILE, 'genre_id'=>6000));
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_ALL, 1, 1, 10, array('join_dsp'=>1, 'genre_id'=>6000));
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_GAME, 1, 1, 10, array('file_id'=>App::APP_FILE_ID_MOBILE, 'order_by'=>'id DESC'));
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_ALL, 1, 1, 10, array('sub_type'=>1));
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_ALL, 1, 1, 10, array('sub_genre'=>7001));
     * App::get_app_list_info($obj_db, App::APP_SUPPORT_IPHONE, App::APP_TYPE_ALL, 1, 1, 10, array('get_total'=>1));
     * @author 李鑫辉
     */
    public static function get_app_list_info( $objDb, 
                                              $intSupport = 3, 
                                              $intType = 1, 
                                              $intOrderBy = 1, 
                                              $intPage = 1, 
                                              $intPageSize = 10, 
                                              $arrData = array() ) {
        
        // Default order
        $arr_order_by  = array(
                               1 => 't1.download DESC, t1.add_time DESC',// 下载量, 添加时间
                               2 => 't1.download DESC, t1.update_time DESC',// 下载量, 更新时间
                               3 => 't1.update_time DESC',// 更新时间
                               4 => 't1.manual_order DESC, t1.download DESC, t1.update_time DESC',// 人工排序, 下载量, 更新时间
                         );
        
        // Bind params
        $arr_bind      = array();
        $str_sql_head  = 'SELECT * FROM ios_apps_info t1';
        $str_where     = ' WHERE t1.status = 1 AND t1.plist_url != \'\'';
        
        // Support
        if ( $intSupport == 1 ) {
            $str_where .= ' AND t1.iphone_no = t1.id';
        } else if ( $intSupport == 2 ) {
            $str_where .= ' AND t1.ipad_no = t1.id';
        }
        
        // Order by 
        if ( ! empty($arrData['order_by']) ) {// Custom order, $intOrderBy = 0
        
            $str_order_by = $arrData['order_by'];
            
        } else if ( ! empty($arr_order_by[$intOrderBy]) ) {
            
            $str_order_by = $arr_order_by[$intOrderBy];
        }
        
        // Type
        if ( $intType == 1 ) {// 游戏应用
        
            $str_where .= ' AND t1.genre_id = ' . self::APP_CATEGORY_ID_GAME;
            
        } else if ( $intType == 2 ) {// 非游戏应用
        
            $str_where .= ' AND t1.genre_id != ' . self::APP_CATEGORY_ID_GAME;
            
        } else if ( $intType == 3 ) {// 推荐应用
        
            $str_where    .= ' AND t1.recommend = 1';
            $str_order_by  = 't1.order_by_re';
            
        } else if ( $intType == 4 ) {// 装机必备
        
            $str_where    .= ' AND t1.essential = 1';
            $str_order_by  = 't1.order_by_es';
            
        } else if ( $intType == 5 ) {// 价格排行
        
            $str_order_by  = 't1.app_price DESC';
        }
        
        // File id, join_dsp
        if ( ! empty($arrData['file_id']) || ! empty($arrData['join_dsp']) ) {
            $str_sql_head  = 'SELECT t2.*, t1.*, t2.update_time as dsp_update_time  FROM ios_apps_info t1';
            $str_sql_body .= ' LEFT JOIN ios_apps_dsp t2 ON(t1.dsp_id=t2.dsp_id)';
            $str_where    .= $arrData['file_id'] > 0 ? ' AND t2.file_id = ' . intval($arrData['file_id']) : '';
        }
        
        // Genre id
        if ( ! empty($arrData['genre_id']) ) {
            $str_where .= ' AND t1.genre_id = ' . intval($arrData['genre_id']);
        }
        
        // Sub genre
        if ( ! empty($arrData['sub_genre']) ) {
            $str_where .= ' AND t1.sub_genre = ' . intval($arrData['sub_genre']);
        }
        
        // Sub type
        if ( $arrData['sub_type'] == 1 ) {// 新增应用
        
            $str_where .= ' AND t1.add_time > \'' . date('Y-m-d 00:00:00', strtotime('-7 day')) . '\'';
            
        } else if ( $arrData['sub_type'] == 2 ) {// 热门应用
            
            $str_where    .= ' AND t1.download > 5';
        }
        
        // App ids
        if ( ! empty($arrData['app_ids']) ) {
            $str_where .= ' AND t1.id IN( ' . $arrData['app_ids'] . ')';
        }
        
        // App id
        if ( ! empty($arrData['app_id']) ) {
            $str_where .= ' AND t1.id = ' . intval($arrData['app_id']);
        }

        // Search word
        if ( ! empty($arrData['search_word']) ) {
            $str_where                .= ' AND t1.app_title LIKE :search_word';
            $arr_bind[':search_word']  = '%' . $arrData['search_word'] . '%';
        }

        $str_sql_body  .= $str_where;
        
        // Get total
        if ( $arrData['get_total'] == 1 ) {
            
            $str_sql  = 'SELECT count(*) as total FROM ios_apps_info t1' . $str_sql_body;
            $arr_info = query_mysql($objDb, $str_sql, $arr_bind);
            
            return $arr_info[0]['total'];
        }
        
        $str_sql_body  .= $str_order_by ? ' ORDER BY ' . $str_order_by : '';
        
        // Limit
        $str_sql_body  .= ' LIMIT ' . ($intPage - 1) * $intPageSize . ',' . $intPageSize;
        
        $str_sql        = $str_sql_head . $str_sql_body;

        $arr_info       = query_mysql($objDb, $str_sql, $arr_bind);

        return $arr_info;
    }
    
    /**
     * Get app list info total
     * 
     * @param  $objDb
     * @param  $intSupport
     * @param  $intType
     * @param  $arrData
     * @return array
     * @author 李鑫辉
     */
    public static function get_app_list_info_total( $objDb,
                                                    $intSupport = 3, 
                                                    $intType = 1, 
                                                    $arrData = array() ) {
        
        $arrData['get_total'] = 1;
        
        return self::get_app_list_info($objDb, $intSupport, $intType, null, null, null, $arrData);
    }
    
    /**
     * Get dsp info
     * 
     * @param  $objDb
     * @param  $intDspId
     * @return array
     * @author 李鑫辉
     */
    public static function get_dsp_info( $objDb, $intDspId ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_dsp WHERE dsp_id = :dsp_id';
        $arr_info = query_mysql($objDb, $str_sql, array(':dsp_id'=>$intDspId));
        
        return $arr_info[0];
    }
    
    /**
     * Get dsp info by file id
     * 
     * @param  $objDb
     * @param  $intFileId
     * @return array
     * @author 李鑫辉
     */
    public static function get_dsp_info_by_file_id( $objDb, $intFileId ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_dsp WHERE file_id = :file_id';
        $arr_info = query_mysql($objDb, $str_sql, array(':file_id'=>$intFileId));
        
        return $arr_info;
    }
    
    /**
     * Get all genre info
     * 
     * @param  $objDb 
     * @param  $isIdKey 
     * @return array
     * @author 李鑫辉
     */
    public static function get_all_genre_info( $objDb, $isIdKey = true ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_genre';
        $arr_info = query_mysql($objDb, $str_sql);
        
        if ( $isIdKey ) {
            $arr_info = set_array_key($arr_info, 'ID');   
        }
        
        return $arr_info;
    }
    
    /**
     * Get genre info
     * 
     * @param  $objDb
     * @param  $intGenreId
     * @return array
     * @author 李鑫辉
     */
    public static function get_genre_info( $objDb, $intGenreId ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_genre WHERE id = :id';
        $arr_info = query_mysql($objDb, $str_sql, array(':id'=>$intGenreId));
        
        return $arr_info[0];
    }
    
    /**
     * Get genre name
     * 
     * @param  $objDb
     * @param  $intGenreId
     * @return array
     * @author 李鑫辉
     */
    public static function get_genre_name( $objDb, $intGenreId ) {
        
        $str_sql  = 'SELECT genre FROM ios_apps_genre WHERE id = :id';
        $arr_info = query_mysql($objDb, $str_sql, array(':id'=>$intGenreId));
        
        return $arr_info[0]['genre'];
    }

    /**
     * Get genre info by parent id
     * 
     * @param  $objDb
     * @param  $intParentId
     * @return array
     * @author 李鑫辉
     */
    public static function get_genre_info_by_parent_id( $objDb, $intParentId = 0 ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_genre WHERE parent_id = :parent_id';
        $arr_info = query_mysql($objDb, $str_sql, array(':parent_id'=>$intParentId));
        
        return $arr_info;
    }
    
    /**
     * Get link info
     * 
     * @param  $objDb
     * @return array
     * @author 李鑫辉
     */
    public static function get_all_link_info( $objDb ) {
        
        $str_sql  = 'SELECT * FROM ios_apps_link';
        $arr_info = query_mysql($objDb, $str_sql);
        
        return $arr_info;
    }
    
    /**
     * Get app pic
     * 
     * @param  $strPic
     * @return array
     * @author 李鑫辉
     */
    public static function get_app_pic( $strAppPic ) {
        
        return split_str($strAppPic);
    }
    
    /**
     * Get app url
     * 
     * @param  $strPic
     * @return array
     * @author 李鑫辉
     */
    public static function get_app_url( $strAppUrl ) {
        
        return split_str($strAppUrl);
    }
    
    /**
     * Get app icon
     * 
     * @param  $strAppIcon
     * @param  $isReplaceUrl
     * @return array
     * @author 李鑫辉
     */
    public static function get_app_icon( $strAppIcon, $isReplaceUrl = true ) {
        
        $str_url = split_str($strAppIcon);
        
        return $isReplaceUrl ? str_replace('iosfile.izhushou.cn', self::get_cdn_url(), $str_url) : $str_url;
    }
    
    /**
     * Get cdn url
     * 
     * @param  $isRand
     * @return string
     * @author 李鑫辉
     */
    public static function get_cdn_url( $isRand = true ) {
        
        $arr_cdn_url = self::$_cdn_url;
        
        if ( $isRand ) {
            shuffle($arr_cdn_url);
        }
        
        return $arr_cdn_url[0];
    }
    
    /**
     * Get cdn url array
     * 
     * @param  void
     * @return array
     * @author 李鑫辉
     */
    public static function get_cdn_url_array() {
        
        return self::$_cdn_url;
    }
    
    /**
     * Check is app game
     * 
     * @param  $strCategoryId
     * @return bool
     * @author 李鑫辉
     */
    public static function is_app_game( $strCategoryId ) {
        
        return self::APP_CATEGORY_ID_GAME == $strCategoryId;
    }
}

